/**
 * Copyright (C) 2022 - 长期
 * All rights reserved.
 * <p>
 * 版权所有 (C) 中国烟草总公司
 */
package com.itzhoun.controller;

import com.itzhoun.model.param.LoginParam;
import com.itzhoun.model.base.Result;
import com.itzhoun.model.pojo.MangerInfo;
import com.itzhoun.service.UserService;
import com.itzhoun.util.JWTUtil;
import com.itzhoun.util.ShiroKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author zhounan
 * @date 2024/01/19 15:14
 * @Description
 */
@RestController
public class LoginController {

    @Resource
    private UserService userService;


    private static final Logger _logger = LoggerFactory.getLogger(LoginController.class);


    @PostMapping("login")
    public Result<String> login(@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType,
                                @RequestBody @Validated LoginParam loginParam){

        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        MangerInfo mangerInfo = userService.findUserByUsername(username);
        if (mangerInfo == null){
            throw new RuntimeException("no user fail");
        }
        //随机数盐
        String salt = mangerInfo.getSalt();
        String encodePassword = ShiroKit.md5(password, username + salt);
        if (!encodePassword.equals(mangerInfo.getPassword())){
            throw new RuntimeException("password error");
        }
        return new Result<>(true, "login success", JWTUtil.sign(username,encodePassword));
    }
}
